package com.gosophia.conference.action.summary;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.gosophia.commons.web.action.BaseSupportAction;
import com.gosophia.commons.web.logAnnotation.LogRecord;
import com.gosophia.conference.action.notification.MyAuthenticator;
import com.gosophia.conferenceManagement.ConferenceTurningAction;
import com.gosophia.conferenceManagement.common.dto.DocumentDTO;
import com.gosophia.conferenceManagement.common.entity.DocumentInfo;
import com.gosophia.conferenceManagement.common.service.ConferenceFileService;
import com.gosophia.conferenceManagement.common.ws.ConferenceQueryWebService;
import com.gosophia.conferenceManagement.summary.dto.SendSummaryJobDataDTO;
import com.gosophia.conferenceManagement.summary.ws.SendSummaryWebService;
import com.gosophia.oa.action.JudgeCurrentUndertaker;
import com.gosophia.springsecurity.UserDetailsImpl;
import com.gosophiaigit.contact.busi.entity.Contact;
import com.gosophiaigit.contact.busi.service.IContactGroupService;
import com.opensymphony.xwork2.ActionContext;

/**
 * 发送邮件action
 * @author mayue
 *
 */
@Scope("prototype")
@Controller("SendSummaryAction")
public class SendSummaryAction extends BaseSupportAction {

    private static final long serialVersionUID = 1L;

    @Autowired
    private SendSummaryWebService sendSummaryWebService;
    
    @Autowired
    private ConferenceQueryWebService conferenceQueryWebService;
    
    @Autowired
    private JudgeCurrentUndertaker judgeCurrentUndertaker;
    
    @Autowired
    private ConferenceFileService conferenceFileService; 
    
    @Autowired
    private IContactGroupService iContactGroupService;
    
    private SendSummaryJobDataDTO sendSummaryJobDataDTO;
    
    private List<Long> oldDocumentIds;
    @Override
    @LogRecord(eventAction="会议管理-会议总结-发送总结",eventTarget="sendSummaryJobDataDTO")
    public String _execute() throws Exception {
        //判断当前用户和job承办人是否匹配,如果不匹配转到异常页面
        judgeCurrentUndertaker.judgeOperationAuthority(sendSummaryJobDataDTO.getJobDTO().getJobId());
        
        UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder
        .getContext().getAuthentication().getPrincipal();
        
        Long operatorId = userDetails.getUserAccountDTO().getUserInfoDTO()
        .getUserInfoId();
        List<DocumentDTO> oldDocumentList = new ArrayList<DocumentDTO>();
        List<File> sendFiles = new ArrayList<File>();
        //附件
        if(oldDocumentIds!=null&&oldDocumentIds.size()!=0){
            for(Long id:oldDocumentIds){
                DocumentDTO docDTO = conferenceQueryWebService.findDocumentByDocumentId(id);
                if(docDTO!=null){
                    DocumentDTO docNoId = new DocumentDTO();
                    docNoId.setDocumentCategory(docDTO.getDocumentCategory());
                    docNoId.setDocumentName(docDTO.getDocumentName());
                    docNoId.setDocumentNote(docDTO.getDocumentNote());
                    docNoId.setDocumentPath(docDTO.getDocumentPath());
                    docNoId.setDocumentVersion(docDTO.getDocumentVersion());
                    oldDocumentList.add(docNoId);
                    DocumentInfo docInfo =conferenceFileService.loadDocumentByPath(docDTO.getDocumentPath());
                    InputStream fileIo = docInfo.getDocumentContent();
                    File f1=new File("c:/"+docDTO.getDocumentName());
                    FileOutputStream o=new FileOutputStream(f1);  
                    byte b[]=new byte[4000];
                    int n;
                    while((n=fileIo.read(b))!=-1)  
                    {o.write(b,0,n);  
                    }
                    o.close(); 
                    fileIo.close();
                    sendFiles.add(f1);
                }
            }
            
        }
        sendSummaryJobDataDTO.setAttachmentsDTOs(oldDocumentList);
        //在线文档
        if(sendSummaryJobDataDTO!=null && sendSummaryJobDataDTO.getOnlineDocumentDTO()!=null){
            //设置在线文档类型
            sendSummaryJobDataDTO.getOnlineDocumentDTO().setDocumentCategory("online");
        }
        
        List<String> sendTo = new ArrayList<String>();
//        if(sendSummaryJobDataDTO.getRecipientIds()!=null){
//            for(Long recipientId:sendSummaryJobDataDTO.getRecipientIds()) {
//                List<UserInfoDTO> userInfoDtos = userManagementWebService.findAllUserInfo();
//                for(UserInfoDTO userInfoDTO:userInfoDtos) {
//                    if(recipientId.equals(userInfoDTO.getUserInfoId())) {
//                        if(userInfoDTO.getEmail()!=null){
//                            sendTo.add(userInfoDTO.getEmail());
//                        }
//                    }
//                }
//            }
//        }
        if(sendSummaryJobDataDTO.getRecipientIds()!=null){
            for(Long recipientId:sendSummaryJobDataDTO.getRecipientIds()) {
                List<Contact> contacts = iContactGroupService.findAllContactList();
                if(contacts!=null && contacts.size()!=0){
                    for(Contact contact:contacts) {
                        if(recipientId.equals(contact.getUserInfoId())) {
                            if(contact.getEmail()!=null){
                                sendTo.add(contact.getEmail());
                            }
                        }
                    }
                }
            }
        }
        
        //获取在线文档
        if(sendSummaryJobDataDTO.getOnlineDocumentDTO().getDocumentPath()!=null&&!"".equals(sendSummaryJobDataDTO.getOnlineDocumentDTO().getDocumentPath())){
            DocumentInfo docInfo =conferenceFileService.loadDocumentByPath(sendSummaryJobDataDTO.getOnlineDocumentDTO().getDocumentPath());
            InputStream fileIo = docInfo.getDocumentContent();
            File f1=new File("c:/会议总结附件.doc");
            FileOutputStream o=new FileOutputStream(f1);  
            byte b[]=new byte[4000];
            int n;
            while((n=fileIo.read(b))!=-1)  
            {o.write(b,0,n);  
            }
            o.close(); 
            fileIo.close();
            sendFiles.add(f1);
        }
        //邮件的文本内容，可以包含html标记则显示为html页面 
        String content = "会议总结附件";
        String title = "会议总结";//所发送邮件的标题
        if(sendmail(title,sendTo,content,"text/html;charset=gbk",sendFiles)){
           for(File file:sendFiles){
               if(file.exists()) {
                   file.delete();  
               }
           }
        }
        sendSummaryJobDataDTO.setTurningAction(ConferenceTurningAction.DEFAULT_ACTION.getValue());
        sendSummaryWebService.HandleConferenceTurningSummary(sendSummaryJobDataDTO.getJobDTO().getJobId(), operatorId, sendSummaryJobDataDTO);
        
        super.getRequestResult().setRsltCode("0");
        super.getRequestResult().setMessage("会议总结发送成功");
        ActionContext.getContext().getSession().put("_lastOpResult", super.getRequestResult());
        
        if("task".equals(this.getFromFlag())){
            return "task";
        }
        return SUCCESS;
    }
    
    public static boolean sendmail(String subject, List<String> to, String text, String mimeType,List<File> sendFiles) throws Exception 
    { 
    //ResourceBundle mailProps = ResourceBundle.getBundle("mail"); 可以从配置文件读取相应的参数 
    
    //得到spring的context对象
    ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:conference-sendMail.xml");
    JavaMailSenderImpl  javaMailSenderImpl = (JavaMailSenderImpl)ctx.getBean("mailSender");
    String smtp = javaMailSenderImpl.getHost();

    String servername = javaMailSenderImpl.getUsername(); 
    String serverpaswd = javaMailSenderImpl.getPassword();

    javax.mail.Session mailSession; //邮件会话对象 
    javax.mail.internet.MimeMessage mimeMsg; //MIME邮件对象 

    Properties props = new Properties(); 
    props = java.lang.System.getProperties(); //获得系统属性对象 
    props.put("mail.smtp.host", smtp); //设置SMTP主机 
    props.put("mail.smtp.auth", "true"); //是否到服务器用户名和密码验证 
    String from = javaMailSenderImpl.getUsername(); 
    MyAuthenticator myEmailAuther = new MyAuthenticator(servername, serverpaswd);
    try {
        //设置邮件会话 
        mailSession = javax.mail.Session.getInstance(props, (Authenticator) myEmailAuther);  
        //设置传输协议 
        Transport transport = mailSession.getTransport("smtp");
        //设置from、to等信息 
        mimeMsg = new javax.mail.internet.MimeMessage(mailSession); 
        if (!StringUtils.isEmpty(from)) 
        { 
        InternetAddress sentFrom = new InternetAddress(from); 
        mimeMsg.setFrom(sentFrom); //设置发送人地址 
        } 

        InternetAddress[] sendTo = new InternetAddress[to.size()]; 
        for (int i = 0; i < to.size(); i++) 
        { 
        sendTo[i] = new InternetAddress(to.get(i)); 
        } 

        mimeMsg.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo); 
        mimeMsg.setSubject(subject, "gbk"); 
        //MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象   
        Multipart mainPart = new MimeMultipart();   
        //创建一个包含HTML内容的MimeBodyPart   
        BodyPart html = new MimeBodyPart();   
        //设置HTML内容   
        html.setContent(text,"text/html; charset=gbk");   
        mainPart.addBodyPart(html);   
        // 将MiniMultipart对象设置为邮件内容   
        mimeMsg.setContent(mainPart);
        for(int i=0;i<sendFiles.size();i++){
          html=new MimeBodyPart();
          FileDataSource fds=new FileDataSource(sendFiles.get(i).getAbsolutePath());
          html.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart
          String displayfilename = MimeUtility.encodeWord(sendFiles.get(i).getName(),"utf-8", null);
          html.setFileName(displayfilename);  //得到文件名同样至入BodyPart      
          mainPart.addBodyPart(html);   
        }
//        for(String f:filenames){   
//            html=new MimeBodyPart();
//            FileDataSource fds=new FileDataSource(f);
//            html.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart
//            String displayfilename = MimeUtility.encodeWord("会议总结附件.doc","utf-8", null);
//            html.setFileName(displayfilename);  //得到文件名同样至入BodyPart      
//            mainPart.addBodyPart(html);      
//        }   
        // 将MiniMultipart对象设置为邮件内容   
        mimeMsg.setContent(mainPart);
        //设置信件头的发送日期 
        mimeMsg.setSentDate(new Date()); 
        mimeMsg.saveChanges(); 
        //发送邮件 
        Transport.send(mimeMsg); 
        transport.close();
        return true; 
    } catch (MessagingException ex) {   
        ex.printStackTrace();   
    }   
    return false;
    } 
    
    public SendSummaryJobDataDTO getSendSummaryJobDataDTO() {
        return sendSummaryJobDataDTO;
    }
    public void setSendSummaryJobDataDTO(SendSummaryJobDataDTO sendSummaryJobDataDTO) {
        this.sendSummaryJobDataDTO = sendSummaryJobDataDTO;
    }
    public List<Long> getOldDocumentIds() {
        return oldDocumentIds;
    }
    public void setOldDocumentIds(List<Long> oldDocumentIds) {
        this.oldDocumentIds = oldDocumentIds;
    }

}
